<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 头部组件 -->
      <HeadCard :show-before="true">
        <template #before>
          <el-button
            type="primary"
            size="small"
            @click="isShowDialog=true"
          >添加客户</el-button>
        </template>
        <template #after>
          <el-select v-model="tableData.agent" placeholder="请选择" @change="selectChange">
            <el-option
              v-for="(item,index) in tableData"
              :key="index"
              :value="item.agent?item.agent.id:1"
              :label="item.agent?item.agent.name:'111'"
            />
          </el-select>
          <el-input v-model="search" placeholder="请输入关键字" />
          <el-button size="small" @click="searchBtn">筛选</el-button>
          <el-button size="small" :disabled="isDisabled" @click="allListBtn">总列表</el-button>
        </template>
      </HeadCard>
      <el-card class="card">
        <el-table :data="tableData">
          <el-table-column label="图片">
            <template #default="{ row }">
              <img v-fixImg="require(`@/assets/common/1.jpg`)" :src="row.image" alt="">
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="name" />
          <el-table-column label="邮箱" prop="email" />
          <el-table-column label="电话" prop="phone" />
          <el-table-column label="经纪" prop="agent.name" />
          <el-table-column label="微信" prop="wechat" />
          <el-table-column label="介绍" prop="desc" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button
                type="primary"
                size="small"
                @click="editCustomer(row.id)"
              >编辑</el-button>
              <el-button type="danger" size="small" @click="delCustomer(row.id)">删除</el-button>
            </template>

          </el-table-column></el-table>
      </el-card>
      <!-- 分页组件 -->

      <el-row type="flex" justify="center">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="page.pageSize"
          :current-page="page.page"
          @current-change="currentCahnge"
        />
      </el-row>

      <!-- 弹窗 -->
      <el-dialog
        title="新增客户"
        :visible="isShowDialog"
        @close="cancelBtn"
      >
        <el-form ref="formData" :model="formData" :rules="rules">
          <el-form-item label="经纪" prop="agent">
            <el-select v-model="formData.agent" size="small">
              <el-option
                v-for="(item,index) in tableData"
                :key="item.id"
                :label="item.agent?item.agent.name:'111'"
                :value="item.agent?item.agent.id:index"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" style="width: 80%" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" style="width: 80%" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="formData.phone" style="width: 80%" />
          </el-form-item>
          <el-form-item label="微信" prop="wechat">
            <el-input v-model="formData.wechat" style="width: 80%" />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="formData.desc" style="width: 80%" />
          </el-form-item>
          <el-form-item label="封面" prop="image">
            <ImageUpload ref="IMG" @image="image" />
          </el-form-item>
        </el-form>
        <el-row type="flex" justify="end">
          <el-button size="small" type="primary" @click="sendBtn">确定</el-button>
          <el-button @click="cancelBtn">取消</el-button>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getcustomerList, newCustomer, delCustomer, getCustomer, editCustomer, getcustomer } from '@/api/customer'
export default {
  data() {
    return {
      isDisabled: false, // 禁止按钮
      // 分页
      page: {
        pageSize: 3, // 每页显示条数
        page: 1 // 默认第一页
      },
      search: '', // 头部搜索框的值
      agent: '', // 用于绑定头部下拉框的id
      selectVal: '111', // 下拉框内容
      limit: 3, // 显示的条数
      start: 0, // 从第几条开始显示
      total: 0, // 总条数
      customerId: '', // 经纪人id
      isShowDialog: false, // 弹窗显示
      tableData: [], // 用于接收渲染页面请求
      formData: {
        agent: { }, // 属于哪个经纪的 id 值
        name: '', // 名称
        email: '', // 电子邮箱，比如 example@qq.com
        phone: '', // 电话
        wechat: '', // 微信
        desc: '', // 描述
        image: '' // 图片
      },
      // 校验规则
      rules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { pattern: /^([a-zA-Z0-9]+[-_.]?)+@[a-zA-Z0-9]+.[a-z]+$/, message: '请输入正确的邮箱', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '电话号码不能为空', trigger: 'blur' },
          { pattern: /^1[3-9][0-9]{9}$/, message: '请输入正确的电话号', trigger: 'blur' }
        ],
        wechat: [
          { required: true, message: '微信号不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getcustomerList()
    this.totalList()
  },
  methods: {
    // 渲染总条数
    async totalList() {
      this.total = await getcustomer()
      // console.log(158, this.total)
    },
    // 渲染页面列表
    async getcustomerList() {
      this.tableData = await getcustomerList({
        _limit: this.limit,
        _start: this.start,
        name_contains: this.search
      })
      // console.log(this.tableData)
    },
    // 编辑按钮
    async editCustomer(id) {
      this.isShowDialog = true
      // this.formData = await getCustomer(id)
      const res = await getCustomer(id)
      // console.log(res, 204)
      if (res.image) {
        this.$nextTick(() => {
        // console.log(131, this.$refs.IMG)
          this.$refs.IMG.fileList = [{ url: this.formData.image }]
        })
      }

      this.formData = res

      // console.log(130, this.formData.image)
    },
    // 弹窗确定按钮
    async sendBtn() {
      console.log(this.formData, 196)
      await this.$refs.formData.validate()
      if (this.formData.id) {
        // 编辑
        await editCustomer(this.formData)
      } else {
        // 新增
        await newCustomer(this.formData)
      }
      // 提示用户
      this.$message.success('操作成功!')
      // 渲染页面
      this.getcustomerList()
      // 渲染分页总数
      this.totalList()
      // 关闭弹窗
      this.isShowDialog = false
    },
    // 弹窗取消按钮
    cancelBtn() {
      // 清空表单校验
      this.$refs.formData.resetFields()
      // 取消时清空数据
      this.formData = {
        agent: { }, // 属于哪个经纪的 id 值
        name: '', // 名称
        email: '', // 电子邮箱，比如 example@qq.com
        phone: '', // 电话
        wechat: '', // 微信
        desc: '', // 描述
        image: [] // 图片
      }
      // 清空上传组件的图片
      // console.log(this.$refs.IMG)
      // 清空子组件的图片
      this.$refs.IMG.fileList = []
      // 关闭弹窗
      this.isShowDialog = false
    },
    // 删除事件
    async delCustomer(id) {
      await this.$confirm('是否确定删除')
      await delCustomer(id)
      // 提示用户
      this.$message.success('操作成功！')
      this.$nextTick(() => {
        // console.log(this.tableData.length)
        if (this.tableData.length === 1) {
          // 当前页数据被删除完毕后返回到上一页
          this.page.page - 1
          // console.log(248, this.start)
          // 把当前页的数据减去需要显示的页面就能返回到上一页的数据
          this.start = this.start - this.page.pageSize
          // console.log(250, this.start)
        }
        // 渲染总条数
        this.totalList()
        // 渲染页面
        this.getcustomerList()
      })
    },
    // 子传父的值
    image(val) {
      // console.log(152, val)
      this.formData.image = val
      console.log(154, this.formData.image)
    },
    // 分页功能
    currentCahnge(page) {
      console.log(page)
      // 把最新的页数传给当前页
      this.page.page = page
      this.start = (page - 1) * this.limit
      // 重新渲染
      this.getcustomerList()
    },
    // 筛选按钮
    async searchBtn() {
      // 判断是否有值  下拉框跟输入框都没值时点击筛选触发消息提示
      if (!this.agent && !this.search) {
        console.log('两个都没有')
        this.$message.error('请输入搜索内容')
        return
      }
      // 用于修复跳转到其它页面后搜索不到前面页数的数据
      this.page = {
        pageSize: 3, // 每页显示条数
        page: 1 // 默认第一页
      }
      // 从第1条数据开始渲染
      this.start = 0
      // this.getcustomerList()

      if (this.agent) {
        // 下拉框有选中  有id
        // console.log('11')
        this.tableData = await getcustomerList({
          _limit: this.limit,
          _start: this.start,
          name_contains: this.search,
          agent: this.agent
        })
        // 解决页数没刷新问题
        // 获取筛选后的总数
        this.total = await getcustomer({
          _limit: this.limit,
          _start: this.start,
          name_contains: this.search,
          agent: this.agent
        })
      } else {
        // console.log('22')
        // 下拉框没值，没选中  没id
        this.tableData = await getcustomerList({
          _limit: this.limit,
          _start: this.start,
          name_contains: this.search
        // agent: this.customerId
        })
        // 解决页数没刷新问题
        // 获取筛选后的总数
        this.total = await getcustomer({
          _limit: this.limit,
          _start: this.start,
          name_contains: this.search
        })
      }
      // 清除内容
      this.search = ''
      // console.log(this.total, 321)
    },
    // 总列表
    allListBtn() {
      // this.getcustomerList()
      this.isDisabled = true
      setTimeout(() => {
        this.isDisabled = false
      }, 3000)
      this.getcustomerList()
      this.totalList()
    },
    // 头部下拉搜索框事件
    selectChange(val) {
      // 把下拉框的id赋值给变量 利用它发带id的参数请求
      this.agent = val
    }
  }
}
</script>

<style scoped>
.card {
  margin-right: 20px;
  margin-left: 20px;
}
img {
  width: 90%;
}
el-input {
  width: 200px;
}
</style>
